const express = require("express");
const bodyParser = require('body-parser');
const db = require("./module/db");
const tools = require("./module/tools");
const {upPic} = require("./module/upPic");
const mongodb = require("mongodb")
const app = express();
const shopType = require("./module/shopType");
const shopList = require("./module/shopList");
const goodsType = require("./module/goodsType");
const goodsList = require("./module/goodsList");

app.use(bodyParser.json());
app.use(express.static(__dirname+"/upload"))

let adminInfo = null;
// 登陆
app.post("/login",async function (req,res) {
    // 接收需要先安装body-parser，然后在引入
    const {adminName,passWord} = req.body;
    // console.log(adminName,passWord)
    // 根据账号和密码进行登陆，需要与你的数据库当中的文档进行匹配

    // 用户登录
    
    const personnerResults=await db.findOne("personnerList",{
        adminName,
        passWord:tools.enMd5(passWord)
    })
   
    // 用户登录的结果
    if(personnerResults){
        await db.insertOne("personnerLog",{
            adminId:personnerResults._id,
            adminName:personnerResults.adminName,
            loginTime:Date.now()
        })
        res.json({
            ok:1,
            status:0,
            adminName:personnerResults.adminName,
            token:tools.encode({
                adminName:personnerResults.adminName
            })
        })
    }else{
        const results = await db.findOne("adminList",{
            adminName,
            passWord:tools.enMd5(passWord)
        })
    
        // 管理员登陆的结果
            // console.log(111,results)
            if(results){
                // console.log(results)
                await db.insertOne("adminLog",{
                    adminId:results._id,
                    adminName:results.adminName,
                    loginTime:Date.now()
                })
                res.json({
                    ok:1,
                    status:1,
                    adminName:results.adminName,
                    token:tools.encode({
                        adminName:results.adminName
                    })
                })
            }else{
                tools.json(res,-1,"账号或密码错误")
            }
    }  
    
       // 管理员登录
     
       
  
});
app.all("*",function (req,res,next) {
    // 验证token
    // console.log(123)
    const deResult = tools.decode(req.headers.authorization);
    // console.log(deResult)
    if(deResult.ok === 3){
        adminInfo = deResult.info;
        next();
    }
    else{
        tools.json(res,2,"接口请求异常")
    }
})
app.get("/adminLog",async function (req,res) {
    const adminName = adminInfo.adminName;
    // console.log(req.query)
    let pageIndex = req.query.pageIndex/1;
    // console.log(pageIndex)
    let pageSum = 1;
    let limit = 3;
    const count = await db.count("adminLog",{
        adminName
    });
    pageSum = Math.ceil(count/limit);
    if(pageSum < 1)
        pageSum = 1;
    if(pageIndex > pageSum)
        pageIndex = pageSum;
    if(pageIndex < 1)
        pageIndex = 1;
    const adminLog = await db.find("adminLog",{
        whereObj:{
            adminName
        },
        sortObj:{
            loginTime:-1
        },
        skip:(pageIndex-1)*limit,
        limit
    });
    // setTimeout(()=>{
    res.json({
        ok:1,
        adminLog,
        pageIndex,
        pageSum
    })
    // },2000)


});

app.get("/personnerLog",async function (req,res) {
    const adminName = adminInfo.adminName;
    
    // console.log(req.query)
    let pageIndex = req.query.pageIndex/1;
    // console.log(pageIndex)
    let pageSum = 1;
    let limit = 3;
    const count = await db.count("personnerLog",{
        adminName
    });
    // console.log(count)
    pageSum = Math.ceil(count/limit);
    if(pageSum < 1)
        pageSum = 1;
    if(pageIndex > pageSum)
        pageIndex = pageSum;
    if(pageIndex < 1)
        pageIndex = 1;
    const personnerLog = await db.find("personnerLog",{
        whereObj:{
            adminName
        },
        sortObj:{
            loginTime:-1
        },
        skip:(pageIndex-1)*limit,
        limit
    });
    // setTimeout(()=>{
    res.json({
        ok:1,
        personnerLog,
        pageIndex,
        pageSum
    })
    // },2000)


});
/*********************部门列表*********************/
//上传图片，上传部门名字
app.post("/shopType",shopType.addShopType)
//获取部门列表
app.get("/shopTypeList",shopType.getShopTypeList)
//获得所有部门的信息
app.get("/allShopTypeList",shopType.getAllShopTypeList);
app.get("/shopListByTypeId/:shopTypeId",shopType.getShopListByTypeId)
app.get("/getShopTypeById",shopType.getShopTypeById);
app.put("/shopTypeList",shopType.putShopTypeList);
/***********************组列表*********************/
//添加组接口
app.post("/shopList",shopList.addShopList)
//获取组列表
app.get("/shopList",shopList.getShopList)
app.get("/shopListById",shopList.getShopListById)
/************************职位列表************************/
//添加职位
app.post("/goodsTypeList",goodsType.addGoodsTypeList)
//获取职位
app.get("/goodsTypeList",goodsType.getGoodsTypeList)
app.get("/goodsListByTypeId/:shopId",goodsType.getGoodsListByTypeId)
/**************************员工列表************************/
//添加员工
app.post("/goodsList",goodsList.addGoodsList)
//获取员工
app.get("/goodsList",goodsList.getGoodsList)

//请假
//上传请假信息
app.post("/addContent",async function(req, res){
        // console.log(req.body)
        const {name, content, status}= req.body
        await db.insertOne("askForLeave",{
            name,
            content,
            askForLeaveTime:Date.now(),
            status
        })
        res.json({
            ok:1,
        })
   
})  
//获取请假信息
app.get("/askForLeaveList",async function(req, res){

     let pageIndex = req.query.pageIndex/1;
    // console.log(pageIndex)
    let pageSum = 1;
    let limit = 3;
    const count = await db.count("askForLeave");
    // console.log(count)
    pageSum = Math.ceil(count/limit);
    if(pageSum < 1)
        pageSum = 1;
    if(pageIndex > pageSum)
        pageIndex = pageSum;
    if(pageIndex < 1)
        pageIndex = 1;
    const data= await db.find("askForLeave", {
        sortObj:{
            askForLeaveTime:-1
         },
        skip:(pageIndex-1)*limit,
        limit
    }) 
    // console.log(data)

    res.json({
        ok:1,
        data,
        pageIndex,
        pageSum
    })
})

//更改请假状态
app.put("/upStatus/:id/:type",function(req,res){
    // console.log(req.params)
    const {id, type}=req.params;
    let $inc = {
        status:-1
    }
    // 如果 类别为1，则顶加1
    if(type/1 === 2){
        $inc = {
            status:1
        }
    }
    
        db.updateOneById("askForLeave",id,{$inc})
            .then(()=>{
                res.json({
                    ok:1,
                    msg:"成功"
                })
            }).catch(()=>{
                res.json({
                    ok:-1,
                    msg:"失败"
                })
        })
   
})



//删除
app.delete("/delete", function (req,res) {
    // console.log(req.query)
    // console.log(req.body)
    const id = req.query.id;
    var path = req.query.path;
    path = path.substr(1)
    // console.log(path)
    if(path==="")
        path="adminLog"
    // if(path==="/goodsList")
    //     path="goodsList"
    // if(path==="/goodsTypeList")
    //     path="goodsTypeList"
    // if(path==="/shopTypeList")
    //     path="shopTypeList"
    // if(path==="/shopList")
    //     path="shopList"
    db.deleteOneById(path,id)
        .then(results=>{
            tools.json(res,1,"成功")
        }).catch(err=>{
        tools.json(res);
    })
})

app.listen(8080,function () {
    console.log("success");
})